import time
import threading
from croniter import croniter
from datetime import datetime


class Crontab:
    _stop = False

    def __init__(self, expression, job, tip=False):
        self.expression = expression
        self.job = job
        self.tip = tip

    def run(self):
        # 主线程
        threading.Thread(target=self._job).start()

    def stop(self):
        self._stop = True

    def _job(self):
        # 子线程
        last_dt = croniter(self.expression, datetime.now()).get_next(datetime)
        while True:
            next_dt = croniter(self.expression, datetime.now()).get_next(datetime)
            if next_dt != last_dt:
                last_dt = next_dt
                threading.Thread(target=self.job).start()
            time.sleep(1)
            if self.tip:
                print('.', end='')
            if self._stop:
                break


if '__main__' == __name__:
    def f():
        print('run!')


    test = Crontab('* * * * *', f, True)
    test.run()
    time.sleep(5)
    test.stop()
